package com.jctf.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Sequence1 implements MessageListener {

	private NetworkManager n;
	private static final int PORT = 33962;
//	private static final String HOST_NAME = "spoon.dontexist.com";
	private static final String HOST_NAME = "127.0.0.1";

	public static void main(String[] args) {
		try {
			new Sequence1().run();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void run() throws InterruptedException, IOException, ClassNotFoundException {
		System.out.println("Starting Sequence 1. Initializing networking...");
		n = new NetworkManager(HOST_NAME, PORT);
		n.registerMessageListener(this);
		n.start();
		int num = 0;
		while(num < 100) {
			n.sendMessage(new NumberMessage(num));
			n.flush();
			Thread.sleep(50);
			num += 2;	
		}
		System.out.println("Quitting...");
		n.close();
	}

	@Override
	public void messageReceived(Message message) {
		System.out.println("Message received: " + message);
	}

	private class NetworkManager extends NetworkHandler {

		private String server;
		private int port;
		private Socket connection;
		private ObjectInputStream input;
		private ObjectOutputStream output;

		public NetworkManager(String serverAddress, int portNumber) {
			server = serverAddress;
			port = portNumber;
		}

		public void start() throws IOException, ClassNotFoundException {
			connection = new Socket(server, port);
			System.out.println("Connected to server.");
			output = new ObjectOutputStream(connection.getOutputStream());
			output.flush();
			input = new ObjectInputStream(connection.getInputStream());
			System.out.println("Attempting login...");
			output.writeObject(new RequestLoginMessage("uptheirons", "maiden"));
			output.flush();
			while(true) {
				Object message = input.readObject();
				if(message == null)
					continue;
				if(message instanceof ConfirmLoginMessage)
					break;
				else if(message instanceof DenyLoginMessage) {
					System.out.println("Authentication failed... Client aborting.");
					System.exit(1);
				}
			}
			System.out.println("Logged in.");
		}

		public void close() throws IOException {
			connection.close();
		}

		public void sendMessage(Message m) throws IOException {
			output.writeObject(m);
		}

		public void registerMessageListener(MessageListener l) {
			listeners.add(l);
			System.out.println("Sequence 1 added as a listener.");
		}

		public void flush() throws IOException {
			output.flush();
		}

	}

}
